
<template>
  <div id="searchList">

    <div class="scroll-container" @scroll="handleScroll">
      <user-card-list :user-list="userList" />
      <van-loading v-if="isLoading" color="#0094ff" size="24px">加载中...</van-loading>
      <van-empty v-if="!userList || userList.length < 1" image="search" description="暂无匹配用户" />
    </div>

  </div>
</template>

<script setup lang="ts">
import qs from "qs";
import {useRoute} from "vue-router";
import {onMounted, ref} from "vue";
import request from "../../plugins/request.ts";
import UserCardList from "../../components/UserCardList.vue";
import {UserType} from "../../models/user";

const route = useRoute();
const { tags } = route.query;
const userList = ref<UserType[]>([]);
const pageNum = ref(1);
const isLoading = ref(false)
const searchUserByTags = async () => {
  isLoading.value = true
  const result = await request.get('/user/search/tags', {
    params: {
      tagNameList: tags,
      "pageNum": pageNum.value,
      "pageSize": 10,
    },
    paramsSerializer: params => {
      return qs.stringify(params, { indices: false})
    }
  })
  if (result.data) {
    result.data.data.forEach(user => {
      if (user.tags) {
        // 将json字符串转换为数组
        user.tags = JSON.parse(user.tags)
      }
    })
    userList.value = result.data.data;
  }
  isLoading.value = false
}

onMounted(async () => {
  await searchUserByTags()
})
/**
 * 实现页面滚动分页
 */
async function handleScroll(event: Event) {
  const { target } = event;
  const scrollContainer = target as HTMLElement;
  if (scrollContainer) {
    const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
    if (scrollTop + clientHeight >= scrollHeight) { // 到达底部时加载更多
      pageNum.value++
      if (pageNum.value > 10) return;
      // 加载数据的函数
      const result = await request.get('/user/search/tags', {
        params: {
          tagNameList: tags,
          "pageNum": pageNum.value,
          "pageSize": 10,
        },
        paramsSerializer: params => {
          return qs.stringify(params, { indices: false})
        }
      })
      if (result.data) {
        result.data.data.forEach(user => {
          if (user.tags) {
            // 将json字符串转换为数组
            user.tags = JSON.parse(user.tags)
          }
        })
        userList.value.push(...result.data.data);
      }

    }
  }
}

</script>


<style scoped>
.scroll-container {
  height: 560px; /* 或根据需要调整 */
  overflow-y: auto;
}
</style>